package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.context.LoginUserThreadLocal;
import com.atguigu.lease.common.exception.MyBusinessException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName TokenInterceptor
 * @Author heartFade
 * @Date 2025-05-04 16:23
 * @Version 1.0
 * @Description TODO
 **/
@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");
        if(token == null || token.isEmpty())
        {
            throw new MyBusinessException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        Claims claims = JWTUtil.parseToken(token);
        Long id =claims.get("id",Long.class);
      String userName=claims.get("userName",String.class);
        LoginUserContext loginUserContext=new LoginUserContext(id,userName);
        LoginUserThreadLocal.setLoginUserContext(loginUserContext);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       LoginUserThreadLocal.removeLoginUserContext();
    }
}
